import ttree from '@/components/common/TTree.vue'
import * as dutyDescriptionService from '@/services/DutyDescriptionService.js'
import * as organizationService from '@/services/OrganizationService'
import moment from 'moment'
import Vue from 'vue'

export default {
  components: {
    ttree
  },
  props: ['dutylog', 'id'],
  watch: {
    // dutylog: function (value) {
    //   if (this.dutylog == 'createDuty') {
    //     this.detailsOperate = false
    //     this.title = '新建值班总结'
    //     this.adddialog = true
    //   } else if (this.dutylog == 'lookDuty') {
    //     this.detailsOperate = true
    //     this.title = '值班总结详情'
    //     this.adddialog = true
    //   } else if (this.dutylog == 'editDuty') {
    //     this.detailsOperate = false
    //     this.title = '编辑值班日志'
    //     this.adddialog = true
    //   }
    // }
    // '$route' (to, from) {
    //   if (to.query.id) {
    //     this.getData()
    //   }
    // }
  },
  data: function () {
    return {
      adddialog: false,
      form: {
        orgId: '',
        deptId: '',
        starttime: '',
        endtime: '',
        description: '',
        dailyReport: '',
        orgReport: '',
        summary: '',
        usernames: '',
        today: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate(),
      },
      description: [],
      timeout: {},
      dutyTime: '',
      dutyDetail: '',
      weatherDetail: '',
      title: '',
      htmlTitle: '值班总结',
      todo: '',
      dutySummary: '',
      dispatchNum: '11',
      num: '',
      addPerson: false,
      detailsOperate: false,
      // dheight: '688px',
      dheight: '680px',
      /*详情*/
      detail: {
        deptid: '',
        orgid: '',
        usernames: '',
        monitor: [],
        dutytime: [],
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      pickerOptions2: {},
      detailId: '',
      createTime: ''
    }
  },
  mounted () {

    this.adddialog = false
    var value = this.dutylog
    if (value == 'createDuty') {
      this.detailsOperate = false
      this.title = '新建值班总结'
      let saveSum = localStorage.getItem('dutySum')
      let start = new Date()
      let end = new Date(start.getTime() + 3600 * 1000 * 24 * 2)
      let yyyy = start.getFullYear()
      let mm = start.getMonth()
      let dd = start.getDate()
      let yyyye = end.getFullYear()
      let mme = end.getMonth()
      let dde = end.getDate()
      this.detail.dutytime = [new Date(yyyy, mm, dd, 8, 30), new Date(yyyye, mme, dde, 8, 30)]
      if (saveSum) {
        this.detail = JSON.parse(saveSum).detail
        this.description = JSON.parse(saveSum).description
        this.form = JSON.parse(saveSum).form
        this.form.today = new Date()
        this.$nextTick(() => {
          this.lheight = this.$refs.dH.offsetHeight + 'px'
          this.liheight = this.$refs.dH1.offsetHeight + 'px'
        })
      }
      if (this.$profile.olevel == 1) {
        this.detail.orgid = this.$profile.fullname
      } else if (this.$profile.olevel == 0) {
        this.detail.orgid = this.$profile.organiza.name
      } else if (this.$profile.olevel == 2) {
        this.detail.deptid = this.$profile.organiza.name
        organizationService.findById(this.$profile.organiza.parentId).then(res => {
          this.detail.orgid = res.name
        })
      }
      // this.getUser()
      // this.timeout = setTimeout(() => {
      //   this.saveitself()
      // }, 60000)
    } else if (value == 'lookDuty') {
      this.detailsOperate = true
      this.title = '值班总结详情'
      this.getData()
    } else if (value == 'editDuty') {
      this.detailsOperate = false
      this.title = '编辑值班日志'
      this.getData()
    }
  },
  destroyed () {
    clearTimeout(this.timeout)
    // clearInterval(this.timer1)
  },
  methods: {
    saveitself () {
      var arr = [this.form, this.detail]
      localStorage.setItem('mySummary', JSON.stringify(arr))
      this.timeout = setTimeout(() => {
        this.saveitself()
      }, 60000)
    },
    getUser () {
      if (localStorage.getItem('mySummary')) {
        var arr = JSON.parse(localStorage.getItem('mySummary'))
        this.form = arr[0]
        this.detail = arr[1]
      } else {
        this.$axios.get(this.$config['getDutyCount'], {params: {skey: localStorage.getItem('auth')}}).then((res) => {

          this.form.orgReport = res.data.content
        })

        this.$axios.get(this.$config['getDaO'], {params: {skey: localStorage.getItem('auth')}}).then((res) => {

          this.detail.deptid = res.data.content.deptName || ''
          this.detail.orgid = res.data.content.orgName || ''
          this.form.deptId = res.data.content.deptId || ''
          this.form.orgId = res.data.content.orgId || ''

        })

        //       this.$axios.get(this.$config['getDU'],{params:{skey:localStorage.getItem('auth')}}).then((res)=>{
        //         this.detail.usernames=res.data.content[0].names
        //             this.form.groupId=res.data.content[0].groupId
        //             this.form.userArray=res.data.content[0].userArray

        //   })
      }
    },
    // 打印
    printPage () {
      // window.print();
      for (var i of document.head.getElementsByTagName('style')) {
        if (i.media == 'print') {
          i.innerHTML = '@page { size: portrait; }'
        }
      }
      this.$emit('changeWidth', '790px')
      document.getElementById('app').style.display = 'none'
      setTimeout(() => {
        window.print()
        this.$emit('changeWidth', '80%')
        document.getElementById('app').style.display = 'block'
      }, 100)
    },
    add () {
      this.addPerson = true
    },
    close () {
      this.$router.push('/duty-sum')
      this.adddialog = false
      // this.$refs.dutyInfo.lookdetail = false
      this.asd = false
    },
    // close () {
    //   this.addPerson = false
    // },
    close1 () {
      this.addPerson = false
    },
    creatsure () {
      this.addPerson = false
    },
    // cancel () {
    //   this.$emit('close')
    // },
    save () {
      var value = this.dutylog
      var obj1 = {
        dayReports: this.detail.monitor.join(','),
        description: this.form.summary,
        dutyEnd: new Date(this.detail.dutytime[1]),
        dutyStart: new Date(this.detail.dutytime[0]),
        id: this.id,
        organiza: {id: this.$profile.organiza.id}, //  || this.$profile.organiza.id
        today: new Date(this.form.today),
        usernames: this.form.usernames
      }
      if (!this.detail.dutytime[0]) {
        this.$alert('开始时间和结束时间不能为空')
        return false
      } else {
        if (this.detail.dutytime[0] == this.detail.dutytime[1]) {
          this.$alert('开始时间和结束时间不能相同')
          return false
        }
      }
      let form2 = JSON.parse(JSON.stringify(this.form))
      form2.today = ''
      let obj = {detail: this.detail, description: this.description, form: form2}
      localStorage.setItem('dutySum', JSON.stringify(obj))
      this.$message({
        type: 'success',
        message: '保存成功!'
      })
      // dutyDescriptionService.update(obj).then(res => {
      //   if (res) {
      //     this.close()
      //     this.$emit('update')
      //     this.$alert('保存成功', '提示')
      //   }
      // })
      // var arr = [this.form, this.detail]
      // localStorage.setItem('mySummary', JSON.stringify(arr))

    },
    sure () {
      var value = this.dutylog
      if (!this.detail.dutytime[0]) {
        this.$alert('开始时间和结束时间不能为空')
        return false
      } else {
        if (this.detail.dutytime[0] == this.detail.dutytime[1]) {
          this.$alert('开始时间和结束时间不能相同')
          return false
        }
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      var obj = {
        dayReports: this.detail.monitor.join(','),
        description: this.form.description,
        dutyEnd: new Date(this.detail.dutytime[1]),
        dutyStart: new Date(this.detail.dutytime[0]),
        organiza: {id: this.$profile.organiza.id}, //  || this.$profile.organiza.id
        today: new Date(this.form.today),
        usernames: this.form.usernames
      }
      if(this.dutylog == 'createDuty'){
        dutyDescriptionService.create(obj).then(res => {
          if (res) {
            this.close()
            this.$emit('update')
            this.$alert('创建成功', '提示')
          }else {
            this.$alert('创建失败', '提示')
          }
          loading.close()
        })
      }else{
        obj.id = this.detailId
        obj.createTime = this.createTime
        dutyDescriptionService.update(obj).then(res => {
          if (res) {
            this.close()
            this.$emit('update')
            this.$alert('修改成功', '提示')
          }else{
            this.$alert('修改失败', '提示')
          }
          loading.close()
        })
      }

    },
    getData () {
      var that = this
      dutyDescriptionService.searchById(this.id).then(res => {
        this.form.usernames = res.usernames
        if (res.organiza) {
          this.detail.orgid = (res.organiza.level == 1 || res.organiza.level == 0) ? res.organiza.name : ''
          this.detail.deptid = res.organiza.level == 2 ? res.organiza.name : ''
        }else{
          this.detail.orgid = ''
          this.detail.deptid = ''
        }//orgid   deptid
        this.detailId = res.id
        this.createTime = res.createTime
        this.form.usernames = res.usernames
        this.detail.monitor = res.dayReports.split(',')
        this.detail.dutytime = [res.dutyStart ? moment(res.dutyStart).format('YYYY-MM-DD HH:mm:ss') : '', res.dutyEnd ? moment(res.dutyEnd).format('YYYY-MM-DD HH:mm:ss') : '']
        if (res.description) {
          if (this.dutylog == 'lookDuty') {
            this.description = res.description.split('\n')
          } else if (this.dutylog == 'editDuty') {
            try {
              this.form.description = JSON.parse(res.description)
            }
            catch (e) {
              this.form.description = res.description
            }
          }
        }
        this.adddialog = true
      }).then(res => {
        if (this.dutylog == 'lookDuty') {

          var dutyDetail = document.querySelector('.dutyDetail')
          Vue.set(that, 'dheight', dutyDetail.clientHeight + 'px')
          // var dutyDetail = document.querySelector('.disabledIpt')
          // Vue.set(that, 'dheight', dutyDetail.clientHeight + 'px')
        }
      })
      // this.$axios.get(this.$config['searchDutySum'], {
      //   params: {
      //     skey: localStorage.getItem('auth'),
      //     d_id: this.$route.query.id
      //
      //   }
      // }).then((res) => {
      //   this.form.usernames = res.data.content[0].usernames
      //   this.detail.deptid = res.data.content[0].deptName || ''
      //   this.detail.orgid = res.data.content[0].orgName || ''
      //   this.detail.dutytime = [res.data.content[0].starttime, res.data.content[0].endtime]
      //   this.form.dId = res.data.content[0].dId
      //   this.form.groupId = res.data.content[0].groupId
      //   this.form.userArray = res.data.content[0].userArray
      //   this.form.deptId = res.data.content[0].deptId || ''
      //   this.form.orgId = res.data.content[0].orgId || ''
      //   this.form.orgReport = res.data.content[0].orgReport
      //   // this.form.weather=res.data.content[0].weather
      //   this.form.summary = res.data.content[0].summary
      //   // this.form.needToBeDealtWith=res.data.content[0].needToBeDealtWith
      //   // this.form.description=res.data.content[0].description
      //   this.detail.monitor = res.data.content[0].dailyReport.split(',')
      // }).then(() => {
      //   if (this.detailsOperate) {
      //     this.$nextTick(() => {
      //
      //       this.dheight = this.$refs.det.offsetHeight - 1 + 'px'
      //     })
      //   } else {
      //     this.dheight = '680px'
      //   }
      //
      // })
    },
    dutylogBtn () {

      this.$axios.get('DutyLogGetDutyLogLast', {
        params: {
          skey: localStorage.getItem('auth'),
        }
      }).then((res) => {
        var data = res.data.content

        for (var i of data) {
          this.form.usernames = i.usernames
          this.detail.dutytime = [i.starttime, i.endtime]
          this.form.summary = i.description
        }
      })

    }

  }
}
